package com.jiayou.config.vertx.handler.jwt

import io.vertx.core.Handler
import io.vertx.core.json.JsonObject
import io.vertx.ext.auth.JWTOptions
import io.vertx.ext.auth.jwt.JWTAuth
import io.vertx.ext.web.RoutingContext

/**
@author lishuang
@data   2021-06-25  15:29:23
@info   JWT用户认证
 */
open class JwtAuthenticationHandler(
        private val jwtAuth: JWTAuth,
        private var username: String = "username",
        private var password: String = "password"
) : Handler<RoutingContext> {


    override fun handle(routingContext: RoutingContext) = doAuthentication(routingContext)

    /**
     * 用户认证
     */
    open fun doAuthentication(routingContext: RoutingContext) {
        if ("admin" == routingContext.request().getParam(username) && "admin" == routingContext.request().getParam(password)) {
            val jwtOptions = JWTOptions().setExpiresInSeconds(600).addPermission("*")
            routingContext.response().end(jwtAuth.generateToken(JsonObject().put("username", "admin"), jwtOptions))
        } else {
            routingContext.response().statusCode = 201
            routingContext.response().putHeader("Content-Type", "application/json")
            routingContext.response().end(JsonObject().put("code", 401).put("message", "禁止访问！").put("data", null).encode())
        }
    }
}